package net.lulihu.pangolin.headless.server.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import net.lulihu.pangolin.headless.common.container.annotation.Component;
import net.lulihu.pangolin.headless.common.protocol.ProtocolMessage;
import net.lulihu.pangolin.headless.common.protocol.ProtocolMessageType;
import net.lulihu.pangolin.headless.common.protocol.handler.RegistrationMessageTypeHandlerComponent;
import net.lulihu.pangolin.headless.common.util.ChannelTwoWayBindKit;

/**
 * 服务端代理通道断开消息处理程序
 */
@Slf4j
@Component
public class ServerProxyChannelDisconnectMessageHandler implements RegistrationMessageTypeHandlerComponent {

    @Override
    public byte messageType() {
        return ProtocolMessageType.TYPE_DISCONNECT;
    }

    @Override
    public void handle(ChannelHandlerContext context, ProtocolMessage message) {
        if (log.isInfoEnabled()) log.info("收到客户端代理通道断开消息");

        Channel proxyChannel = context.channel();
        Channel realChannel = ChannelTwoWayBindKit.getBindChannel(proxyChannel);

        if (realChannel != null) {
            // 数据发送完成后再关闭连接，解决http1.0数据传输问题
            realChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }

        // 解除绑定
        ChannelTwoWayBindKit.unbind(proxyChannel, realChannel);

        // 设置可读
        // proxyChannel.config().setOption(ChannelOption.AUTO_READ, true);
        // 关闭代理通道
        proxyChannel.close();

    }


}
